#' Plot Function for lin_reg Objects
#'
#' This function plots the original data points and the fitted regression line from a 'lin_reg' model.
#'
#' @param model An object of class 'lin_reg'.
#' @param newdata A data frame containing new data for prediction. If not provided, predictions will be based on the data used to fit the model.
#' @return A ggplot object showing the original data and the fitted line.
#' @examples
#' x <- rnorm(100)
#' y <- 20 * x + 23 + rnorm(100)
#' data <- data.frame(x = x, y = y)
#' model <- lin_reg(y ~ x, data = data)
#' plot(model)
#' @export
#' @importFrom ggplot2 ggplot geom_point geom_line aes labs theme_minimal
plot.lin_reg <- function(model, newdata = NULL) {
  # 如果没有提供 newdata，则使用原始数据
  if (is.null(newdata)) {
    newdata <- data.frame(x = model$x[, "x"])
  }

  # 计算预测值
  predictions <- predict(model, newdata = newdata)

  # 创建数据框，包含原始数据和预测值
  plot_data <- data.frame(x = newdata$x, y_pred = predictions)

  # 使用 ggplot2 绘制图形
  library(ggplot2)

  ggplot() +
    geom_point(aes(x = model$x[, "x"], y = model$y), color = "blue", alpha = 0.5) +  # 原始数据点
    geom_line(aes(x = plot_data$x, y = plot_data$y_pred), color = "red") +  # 预测值的线
    labs(title = "Linear Regression Predictions",
         x = "X",
         y = "Y") +
    theme_minimal()
}
